package org.exp3;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StuDao {
    private static final String URL = "jdbc:mysql://localhost:3306/experiment3?useSSL=false&serverTimezone=UTC";
    private static final String USER = "mysql";
    private static final String PASS = "050601";

    // 静态块：只加载一次驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC 驱动未找到！");
            e.printStackTrace();
        }
    }

    // 获取所有学生
    public List<Student> getAllStudents() {
        List<Student> list = new ArrayList<>();
        String sql = "SELECT * FROM student";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {

            while (rs.next()) {
                Student stu = new Student(
                        rs.getInt("stuid"),
                        rs.getString("stuname"),
                        rs.getString("stugender"),
                        rs.getString("enrolledyear"),
                        rs.getString("stuphone"),
                        rs.getString("stumajor")
                );
                list.add(stu);
            }
        } catch (SQLException e) {
            logSQLException(e, "获取所有学生时出错");
        }
        return list;
    }

    public Student getStudentById(int id) {
        String sql = "SELECT * FROM student WHERE stuid = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return new Student(
                            rs.getInt("stuid"),
                            rs.getString("stuname"),
                            rs.getString("stugender"),
                            rs.getString("enrolledyear"),
                            rs.getString("stuphone"),
                            rs.getString("stumajor")
                    );
                }
            }
        } catch (SQLException e) {
            logSQLException(e, "根据ID获取学生信息失败");
        }
        return null;
    }

    // 添加学生
    public void addStudent(Student stu) {
        String sql = "INSERT INTO student (stuid, stuname, stugender, enrolledyear, stuphone, stumajor) VALUES (?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, stu.getStuID());
            ps.setString(2, stu.getStuName());
            ps.setString(3, stu.getStuGender());
            ps.setString(4, stu.getEnrolledYear());
            ps.setString(5, stu.getStuPhone());
            ps.setString(6, stu.getStuMajor());

            ps.executeUpdate();
            System.out.println("添加成功！");

        } catch (SQLException e) {
            logSQLException(e, "添加学生时出错");
        }
    }

    // 删除学生（按 stuid）
    public boolean deleteStudent(int id) {
        String sql = "DELETE FROM student WHERE stuid = ?";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, id);
            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("删除成功！");
                return true;
            } else {
                System.out.println("未找到学号为 " + id + " 的学生，删除失败。");
            }

        } catch (SQLException e) {
            logSQLException(e, "删除学生时出错");
        }
        return false;
    }

    // 修改学生信息
    public boolean updateStudent(Student stu) {
        String sql = "UPDATE student SET stuname = ?, stugender = ?, enrolledyear = ?, stuphone = ?, stumajor = ? WHERE stuid = ?";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, stu.getStuName());
            ps.setString(2, stu.getStuGender());
            ps.setString(3, stu.getEnrolledYear());
            if (stu.getStuPhone() == null || stu.getStuPhone().trim().isEmpty()) {
                ps.setNull(4, java.sql.Types.VARCHAR);
            } else {
                ps.setString(4, stu.getStuPhone());
            }
            ps.setString(5, stu.getStuMajor());
            ps.setInt(6, stu.getStuID());
            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("控制台日志: 学生ID " + stu.getStuID() + " 修改成功！");
                return true;
            } else {
                System.out.println("控制台日志: 修改学生信息失败，未找到学号为 " + stu.getStuID() + " 的学生。");
                return false;
            }

        } catch (SQLException e) {
            logSQLException(e, "修改学生信息时出错");
            return false;
        }
    }

    private void logSQLException(SQLException e, String context) {
        System.err.println("=== " + context + " ===");
        System.err.println("数据库 URL: " + URL);
        System.err.println("用户名: " + USER);
        // 注意：绝不打印密码！
        System.err.println("错误类型: " + e.getClass().getSimpleName());
        System.err.println("错误消息: " + e.getMessage());
        System.err.println("SQL 错误码: " + e.getErrorCode());
        System.err.println("SQL 状态码: " + e.getSQLState());
        e.printStackTrace();
    }

}



